import { defineStore } from 'pinia'
import { login as apiLogin, logout as apiLogout } from '@/services/authService'

export const useAuthStore = defineStore('auth', {
  state: () => ({
    token: localStorage.getItem('token') || '',
    userInfo: (() => {
      try {
        return JSON.parse(localStorage.getItem('userInfo') || '{}')
      } catch (error) {
        console.warn('Failed to parse userInfo from localStorage:', error)
        return {}
      }
    })(),
    isAuthenticated: false
  }),

  actions: {
    async login(credentials) {
      try {
        const response = await apiLogin(credentials)
        
        // 验证响应数据格式
        if (!response || typeof response !== 'object') {
          throw new Error('登录响应格式不正确')
        }
        
        // 注意：由于axios拦截器返回的是response.data，我们需要从中获取token
        const responseData = response.data || response
        
        if (!responseData.token) {
          throw new Error('登录响应缺少token字段')
        }
        
        // 验证token是否为字符串
        if (typeof responseData.token !== 'string') {
          throw new Error('token格式不正确')
        }
        
        this.token = responseData.token
        this.userInfo = responseData.userInfo || {}
        
        // 验证userInfo格式（如果存在）
        if (responseData.userInfo && typeof responseData.userInfo !== 'object') {
          throw new Error('用户信息格式不正确')
        }
        
        this.isAuthenticated = true
        
        // 保存到localStorage以支持页面刷新
        localStorage.setItem('token', this.token)
        localStorage.setItem('userInfo', JSON.stringify(this.userInfo))
        
        // 返回完整的响应数据
        return response
      } catch (error) {
        console.error('登录失败:', error)
        this.logout()
        
        // 提供更具体的错误信息
        if (error.response && error.response.status) {
          switch (error.response.status) {
            case 400:
              throw new Error('请求参数错误')
            case 401:
              throw new Error('用户名或密码错误')
            case 500:
              throw new Error('服务器内部错误')
            default:
              throw new Error(`登录失败: ${error.message || '未知错误'}`)
          }
        } else {
          throw new Error(`网络错误: ${error.message || '请检查网络连接'}`)
        }
      }
    },

    logout() {
      this.token = ''
      this.userInfo = {}
      this.isAuthenticated = false
      
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
      
      // 调用API登出
      apiLogout().catch(error => {
        console.error('Logout API error:', error)
      })
    },

    checkAuthStatus() {
      // 检查token是否存在且未过期
      if (this.token && this.userInfo && Object.keys(this.userInfo).length > 0) {
        this.isAuthenticated = true
      } else {
        this.isAuthenticated = false
      }
    }
  }
})